package clientLogin;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jmsTopic.OneMessage;

/**
 * Servlet implementation class RegServlet
 */
public class RegServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		response.setContentType("text/html");
		Client client = new Client();
		JDBCClientDAO DAO = new JDBCClientDAO();
		
		String email = request.getParameter("email");
		
		try {
			String login = request.getParameter("login");
			String pwd = request.getParameter("pwd");
			String ln = request.getParameter("Lastname");
			String fn = request.getParameter("Firstname");
			String addr = request.getParameter("addr1");
			String phone = request.getParameter("phone");
			if ((login.isEmpty()) || (pwd.isEmpty()) || (ln.isEmpty())
					|| (fn.isEmpty()) || (addr.isEmpty()) || (phone.isEmpty())) {
				String nextHtml = "/Fail.html";
				RequestDispatcher dispatcher = getServletContext()
						.getRequestDispatcher(nextHtml);
				dispatcher.forward(request, response);
				return;
			} else {
				if (DAO.searchByLogin(login) == false) {
					client.setAddress(addr);
					client.setEmail(email);
					client.setFirstname(fn);
					client.setLastname(ln);
					client.setLogin(login);
					client.setPwd(pwd);
					client.setPhone(phone);
					DAO.create(client);
					
					// envoyer un ObjectMessage au Topic 
					OneMessage objMsg = new OneMessage();
					objMsg.setFirstname(fn);
					objMsg.setLastname(ln);
					objMsg.setLogin(login);
					
					session.setAttribute("message", objMsg);
					session.setAttribute("login", login);
					session.setAttribute("lastname", ln);
					
					response.sendRedirect("MessagePublisherServlet");

				} else {
					String nextHtml = "/LoginError.html";
					RequestDispatcher dispatcher = getServletContext()
							.getRequestDispatcher(nextHtml);
					dispatcher.forward(request, response);
					return;
				}
			}

		} catch (NullPointerException nFE) {

			nFE.printStackTrace();

		} 

	}

}
